<?php


namespace app\cms\dto;


use app\cms\model\formFieldModel;
use app\cms\model\formModel;
use iflow\Response;
use iflow\Utils\basicTools;

class formContent
{
    public array $content = [];

    private array $form = [];
    private array $data = [];

    /**
     * @param bool $login_edit | 是否验证 前端登录编辑
     * @return static|Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getFormContent(bool $login_edit = false): static|Response
    {
        if (empty($this -> content['form_id'])) return message() -> parameter_error('模型id不能为空');

        // 获取表名
        $this->form = (new formModel) -> getForm($this -> content['form_id']) ?: [];

        if (!$this->form) return message() -> nodata('表单模型不存在');

        if ($login_edit && intval($this->form['login_edit']) === 0) {
            return message() -> unauthorized_error('请先登录后再填写表单信息');
        }

        $formField = (new formFieldModel) -> where([
            'form_id' => $this -> content['form_id']
        ]) -> select() -> toArray();

        if (empty($formField)) return message() -> nodata('表单模型不存在');

        $this->data = [
            'reply_enable' => $this->content['reply_enable'] ?? 1,
            'foreign_uuid' => $this->content['foreign_uuid'] ?? '0',
            'status' => $this->content['status'] ?? 1,
            'update_time' => time()
        ];

        foreach ($formField as $field) {
            if (str_starts_with($field['form_field_name'], 'ex_')) {
                if ($field['form_field_required']) {
                    if (empty($this -> content[$field['form_field_name']])) return message() -> parameter_error("{$field['form_field_as_name']} 不能为空");
                }

                $info = $this -> content[$field['form_field_name']] === '' ? $field['form_field_default'] :$this -> content[$field['form_field_name']];
                $this->data[$field['form_field_name']] = $info;
            }
        }
        return $this;
    }

    /**
     * 获取指定表单
     * @return array
     */
    public function getForm(): array
    {
        return $this->form;
    }

    /**
     * 获取创建数据
     * @return array
     */
    public function create(): array
    {
        $this->data['form_id'] = $this -> content['form_id'];
        $this->data['uuid'] = (new basicTools()) -> create_uuid();
        $this->data['create_time'] = time();
        $this->data['create_by'] = session('userInfo')['uid'];
        return $this->data;
    }

    /**
     * @return array
     */
    public function getData(): array
    {
        return $this->data;
    }
}